

#include <cstring>
#include <arpa/inet.h>

#include "arq_sender.h"
#include "arq_receiver.h"



static int32_t __main_RunAsSender()
{
    volatile bool bRunning = true;
    CARQSender objSender;
    SOCKADDR_UN stPeerAddr;

    std::thread objStatThread = std::thread([&](volatile bool& refRunning){
        while (refRunning)
        {
            objSender.GetStatistics();
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }, std::ref(bRunning));

    stPeerAddr.stAddrIn.sin_family = AF_INET;
    stPeerAddr.stAddrIn.sin_port = htons(8888);
    stPeerAddr.stAddrIn.sin_addr.s_addr = inet_addr("192.168.56.102");

    int32_t iErr = objSender.Init(stPeerAddr, 1024);
    if (iErr == -1)
    {
        printf("Init ARQSender error, %s\n", strerror(errno));

        return 0;
    }
    
    iErr = objSender.Start();
    if (iErr == -1)
    {
        printf("Start ARQSender error\n");
        return 0;
    }

    while (1)
    {
        //std::this_thread::sleep_for(std::chrono::seconds(1));

        void* pMem = objSender.Alloc(32);
        if (pMem == nullptr)
        {
            break;
        }

        (void)memcpy(pMem, "111aaa222bbb333ccc444ddd", sizeof("111aaa222bbb333ccc444ddd"));

        iErr = objSender.Send(pMem, sizeof("111aaa222bbb333ccc444ddd"));
        if (iErr != 0)
        {
            break;
        }
    }

    return 0;
}

static int32_t __main_RunAsReceiver()
{
    volatile bool bRunning = true;
    CARQReceiver objReceiver;
    SOCKADDR_UN stPeerAddr;

    std::thread objStatThread = std::thread([&](volatile bool& refRunning){
        while (refRunning)
        {
            objReceiver.GetStatistics();
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }, std::ref(bRunning));

    stPeerAddr.stAddrIn.sin_family = AF_INET;
    stPeerAddr.stAddrIn.sin_port = htons(8888);
    stPeerAddr.stAddrIn.sin_addr.s_addr = inet_addr("192.168.56.102");

    int32_t iErr = objReceiver.Init(stPeerAddr, 1024);
    if (iErr == -1)
    {
        printf("Init ARQSender error, %s\n", strerror(errno));

        return 0;
    }
    
    iErr = objReceiver.Start();
    if (iErr == -1)
    {
        printf("Start ARQSender error\n");
        return 0;
    }

    while (1)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    return 0;
}

int main(int argc, char** argv)
{
    int iRole = 0;

    if (argc > 1)
    {
        iRole = atoi(argv[1]);
    }

    if (iRole == 0)
    {
        __main_RunAsSender();
    }
    else
    {
        __main_RunAsReceiver();
    }

    return 0;
}